<?php

class RhController extends Zend_Controller_Action
{

    protected $formRh, $fromRhPesquisa, $rh;

    public function init()
    {
        parent::init();
        $cache = Zend_Registry::get('cache');
		if (!$this->formRh = $cache->load('formRh')) {
    		$this->formRh  = new Application_Form_formRh(); 
            $cache->save($this->formRh,'formRh');
        }
		if (!$this->formRhPesquisa = $cache->load('formRhPesquisa')) {
    		$this->formRhPesquisa  = new Application_Form_formRhPesquisa(); 
            $this->formRhPesquisa->submit->setLabel('Pesquisar');
            $cache->save($this->formRhPesquisa,'formRhPesquisa');
        }
        
        $this->rh = new modelRh();
        
    }
    
    public function indexAction()
    {
		$id    = Zend_Filter::filterStatic($this->_getParam('id'), 'int');
        $identity = Zend_Auth::getInstance()->getIdentity();
        if(!$identity){$this->_redirect('default/usuarios/login');}
                
        $this->view->form_pesquisa = $this->formRhPesquisa;
    
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($this->formRhPesquisa->isValid($formData)) {
                $cpf = $this->formRhPesquisa->getValue('cpf');
                $nome = $this->formRhPesquisa->getValue('nome');
                $email = $this->formRhPesquisa->getValue('email');
                
                if($cpf || $nome || $email){
                    $select = $this->rh->select();
                    if($cpf)    { $select->where('cpf=?',$cpf)->orWhere('username=?',$cpf);}
                    if($nome)   { $select->where("CONCAT(firstname,' ',lastname) LIKE ?",'%'.$nome.'%');}
                    if($email)  { $select->where('email=?',$email);}

                    $select->order(array('firstname','lastname'));
                    $select->limit(100);

                    $this->view->rh = $this->rh->fetchAll($select);
                    if(!($total = count($this->view->rh))){
                        $this->view->messages[] = 'Nenhum registro encontrado para a pesquisa atual!';
                    }
                }
            }
        } else
        {
            $select = $this->rh->select()->where('id=?',$id);
            $this->view->rh = $this->rh->fetchAll($select);
        }
    }

    public function detalheAction()
    {
		$user_id    = Zend_Filter::filterStatic($this->_getParam('id'), 'int');
		$order      = Zend_Filter::filterStatic($this->_getParam('order'), 'int');
        $this->view->rh = $this->rh->find($user_id)->current();
        
        $moodle = new mdlCursos();
        $this->view->cursos = $moodle->ListaCursosByUser($user_id,$order);
        $this->view->notas  = $moodle->ListaNotas($user_id);
        $this->view->order  = $order;
        
    }

    public function formAction()
    {
		$id    = Zend_Filter::filterStatic($this->_getParam('id'), 'int');
		
		if ($id) {
			$data = $this->rh->find($id)->current()->toArray();
            if(!isset($data['cpf'])){
                $data['cpf'] = $data['username'];
            }
			$this->formRh->populate($data);
		}
		
		$this->view->form = $this->formRh;
    }

	public function saveAction()
	{
		if ($this->getRequest()->isPost()) {
			
			if ($this->formRh->isValid($this->_getAllParams())) {
				$data = $this->formRh->getValues();
				if (isset($data['id']) && $data['id']) {
                    if(!$data['cpf']){$data['cpf'] = $data['username'];}
					$this->rh->update($data, array('id = ?' => $data['id']));
				} else {
                    $data['username'] = $data['cpf'];
                    $data['auth'] = 'manual';
                    $data['confirmed'] = 1;
                    
                    $atual = $this->rh->pesquisaRh($data['cpf']);
                    if(!$atual){$id = $this->rh->insert($data);}
                    else {
                        $this->view->messages[] = 'O usuário já existe!';
                        $id = $atual->id;
                    }
                    $this->_redirect('default/rh/resetar/id/'.$id);
				}
				
				$this->_redirect('default/Rh/index');
			}
			
			$this->view->form = $this->formRh;
			$this->render('form');
		}
	}

        public function resetarAction()
    {
        $id = Zend_Filter::filterStatic($this->_getParam('id'), 'int');
        $mdl_user = new mdlUser();
        $mdl_user = $mdl_user->find($id)->current();
        $salt    = 'PZzQ~dbFf%[Ojm+eFoc1c191C';
        $mdl_user['password'] = md5($mdl_user['username'].$salt);
        $mdl_user->save();

        Zend_Db_Table::setDefaultAdapter('moodle');
        $user_pref = new Zend_Db_Table('mdl_user_preferences');
        $db = Zend_Db_Table::getDefaultAdapter();
        $select = $db->select()
                ->from('mdl_user_preferences')
                ->where('userid=?',$mdl_user['id'])
                ->where('name=?','auth_forcepasswordchange');
        $pref = $db->fetchRow($select);
        if(!$pref){
            $pref = $user_pref->createRow();
            $pref['userid'] = $mdl_user['id'];
            $pref['name'] = 'auth_forcepasswordchange';
            $pref['value'] = 1;
            $pref->save();
        } else
        {
            $pref = $user_pref->find($pref->id)->current();
            $pref['value'] = 1;
            $pref->save();
        }

        $this->view->mdl_user = $mdl_user;
        $BodyHtml = $this->view->render('rh/reset-email.phtml');
        $this->_helper->Mail($BodyHtml,
                'Seu cadastro na plataforma ANP.net',
                array('email'=>$mdl_user['email'],'nome'=>$mdl_user['firstname'].' '.$mdl_user['lastname']));
        $this->_helper->flashMessenger->addMessage('A senha de '.$mdl_user['firstname'].' '.$mdl_user['lastname'].' foi reiniciada!');
        $this->_helper->flashMessenger->addMessage('Um e-mail de confirmação foi enviado para o usuário.');

        $this->_redirect('default/rh/index/id/'.$id);
    }
    
	public function deleteAction()
	{
        $id = Zend_Filter::filterStatic($this->_getParam('id'), 'int');
        $form = new Application_Form_Confirm();
        $form->setAction('default/rh/delete');
        $form->getElement('id')->setValue($id);
        $mdl_user = new mdlUser();
        $mdl_user = $mdl_user->find($id)->current();
        if ($this->getRequest()->isPost())
        {
            if ($resposta=$this->getRequest()->getPost('sim')) {
                $table = new modelRh();
                $table->delete(array('id = ?' => $id));
                $this->_helper->flashMessenger->addMessage('O cadastro de '.$mdl_user['firstname'].' '.$mdl_user['lastname'].' foi excluído!');
                $this->_redirect('default/Rh/index');
            }
        }
        $this->view->form = $form;
        $this->view->pergunta = 'Deseja excluir o cadastro de <b>'.$mdl_user['firstname'].' '.$mdl_user['lastname'].'</b>?';
        $this->render('confirm');
	}


}